// 课程数据管理器 - 用于智慧课程管理和3D课堂的数据联动
class CourseDataManager {
  constructor() {
    this.courses = new Map()
    this.listeners = new Set()
    this.initializeTestData()
  }

  // 初始化测试数据
  initializeTestData() {
    const aiBasicsCourse = {
      id: 'ai-basics-001',
      title: '人工智能基础',
      description: '介绍人工智能的基本概念、发展历史和应用领域',
      thumbnail: './static/img/fm01.png',
      status: 'published',
      duration: 45,
      teacher: {
        name: '张教授',
        avatar: 'static/img/teacher.png',
        subject: '人工智能'
      },
      // 智慧课程管理中的PPT讲稿数据
      pptSlides: [
        {
          id: 'slide-001',
          title: '课程介绍',
          script: '欢迎大家来到人工智能基础课程。今天我们将一起探索AI的奇妙世界，了解人工智能的基本概念和应用。',
          slideType: 'title',
          displayDuration: 30,
          backgroundColor: '#667eea',
          textColor: '#ffffff',
          keywords: '人工智能,AI,基础,欢迎',
          voiceType: 'female-professional',
          cameraShot: 'medium',
          transition: 'fade'
        },
        {
          id: 'slide-002',
          title: '什么是人工智能？',
          script: '人工智能是计算机科学的一个重要分支，它致力于创造能够模拟人类智能的机器。AI包括机器学习、深度学习和神经网络等核心技术。',
          slideType: 'ppt',
          displayDuration: 45,
          backgroundColor: '#ffffff',
          textColor: '#333333',
          keywords: '定义,机器学习,深度学习,神经网络',
          voiceType: 'male-deep',
          cameraShot: 'ppt-focus',
          transition: 'slide'
        },
        {
          id: 'slide-003',
          title: 'AI发展历史',
          script: '人工智能的发展可以追溯到20世纪50年代，从图灵测试到深度学习，AI经历了多次技术革命。关键节点包括1956年达特茅斯会议、1997年深蓝战胜卡斯帕罗夫、2016年AlphaGo战胜李世石。',
          slideType: 'ppt',
          displayDuration: 60,
          backgroundColor: '#f8f9fa',
          textColor: '#2c3e50',
          keywords: '发展历史,图灵测试,深蓝,AlphaGo',
          voiceType: 'female-professional',
          cameraShot: 'medium-close',
          transition: 'zoom'
        },
        {
          id: 'slide-004',
          title: '机器学习算法',
          script: '机器学习是AI的核心技术，主要分为三大类：监督学习用于分类和回归问题，无监督学习用于聚类和降维，强化学习用于决策优化。',
          slideType: 'ppt',
          displayDuration: 50,
          backgroundColor: '#ffffff',
          textColor: '#333333',
          keywords: '机器学习,监督学习,无监督学习,强化学习',
          voiceType: 'male-deep',
          cameraShot: 'close',
          transition: 'flip'
        },
        {
          id: 'slide-005',
          title: '实际应用案例',
          script: 'AI在各行业都有广泛应用：医疗领域的智能诊断，交通领域的自动驾驶，金融领域的风险控制，教育领域的个性化学习，以及我们日常使用的智能推荐系统。',
          slideType: 'ppt',
          displayDuration: 55,
          backgroundColor: '#f0f2f5',
          textColor: '#2c3e50',
          keywords: '应用案例,医疗,自动驾驶,金融,教育,推荐系统',
          voiceType: 'female-professional',
          cameraShot: 'medium',
          transition: 'slide'
        },
        {
          id: 'slide-006',
          title: '课程总结',
          script: '今天我们学习了人工智能的基础知识，包括AI的定义、发展历史、核心技术和实际应用。希望大家能够深入理解并在实践中应用这些概念。',
          slideType: 'title',
          displayDuration: 35,
          backgroundColor: '#764ba2',
          textColor: '#ffffff',
          keywords: '总结,回顾,实践应用',
          voiceType: 'female-professional',
          cameraShot: 'medium',
          transition: 'fade'
        }
      ],
      // 3D课堂中的讲稿数据（与PPT联动）
      classroomSlides: [],
      // 课程统计数据
      stats: {
        totalSlides: 6,
        totalDuration: 275, // 秒
        studentsEnrolled: 156,
        completionRate: 87,
        averageScore: 85
      },
      // 学习进度跟踪
      progress: {
        currentSlide: 0,
        completedSlides: [],
        timeSpent: 0,
        interactions: 0
      }
    }

    // 生成3D课堂对应的slides数据
    aiBasicsCourse.classroomSlides = this.generateClassroomSlides(aiBasicsCourse.pptSlides)
    
    this.courses.set(aiBasicsCourse.id, aiBasicsCourse)

    // 添加更多测试课程
    this.addMoreTestCourses()
  }

  // 根据PPT讲稿生成3D课堂slides
  generateClassroomSlides(pptSlides) {
    return pptSlides.map((pptSlide, index) => ({
      id: pptSlide.id,
      title: pptSlide.title,
      content: this.convertScriptToHTML(pptSlide.script, pptSlide.keywords),
      slideIndex: index,
      duration: pptSlide.displayDuration,
      voiceScript: pptSlide.script,
      cameraShot: pptSlide.cameraShot || 'medium',
      transition: pptSlide.transition || 'fade',
      backgroundColor: pptSlide.backgroundColor,
      textColor: pptSlide.textColor,
      keywords: pptSlide.keywords ? pptSlide.keywords.split(',') : []
    }))
  }

  // 将讲稿文本转换为HTML格式
  convertScriptToHTML(script, keywords = '') {
    let html = `<p>${script}</p>`
    
    // 根据关键词生成要点列表
    if (keywords) {
      const keywordList = keywords.split(',').map(k => k.trim())
      if (keywordList.length > 1) {
        html += '<ul>'
        keywordList.forEach(keyword => {
          html += `<li>${keyword}</li>`
        })
        html += '</ul>'
      }
    }
    
    return html
  }

  // 添加更多测试课程
  addMoreTestCourses() {
    const courses = [
      {
        id: 'ml-practice-002',
        title: '机器学习实战',
        description: '深入学习机器学习算法，掌握实际应用技能',
        thumbnail: './static/img/fm03.png',
        status: 'draft',
        duration: 60,
        teacher: {
          name: '李博士',
          avatar: 'static/img/teacher2.png',
          subject: '机器学习'
        },
        pptSlides: [
          {
            id: 'ml-slide-001',
            title: '机器学习概述',
            script: '机器学习是人工智能的核心技术，让计算机从数据中自动学习规律。今天我们将学习监督学习、无监督学习和强化学习三大分支。',
            slideType: 'title',
            displayDuration: 35,
            backgroundColor: '#4facfe',
            textColor: '#ffffff',
            keywords: '机器学习,监督学习,无监督学习,强化学习',
            voiceType: 'male-deep',
            cameraShot: 'medium'
          },
          {
            id: 'ml-slide-002',
            title: '线性回归算法',
            script: '线性回归是最基础的监督学习算法，通过找到最佳拟合直线来预测连续值。我们将学习最小二乘法和梯度下降优化方法。',
            slideType: 'ppt',
            displayDuration: 50,
            backgroundColor: '#ffffff',
            textColor: '#333333',
            keywords: '线性回归,最小二乘法,梯度下降,预测',
            voiceType: 'female-professional',
            cameraShot: 'ppt-focus'
          },
          {
            id: 'ml-slide-003',
            title: '决策树算法',
            script: '决策树是一种直观的分类算法，通过一系列判断条件将数据分类。它具有可解释性强、易于理解的特点。',
            slideType: 'ppt',
            displayDuration: 45,
            backgroundColor: '#f8f9fa',
            textColor: '#2c3e50',
            keywords: '决策树,分类算法,可解释性,判断条件',
            voiceType: 'male-deep',
            cameraShot: 'close'
          }
        ],
        stats: {
          totalSlides: 3,
          totalDuration: 130,
          studentsEnrolled: 89,
          completionRate: 92,
          averageScore: 88
        }
      },
      {
        id: 'dl-advanced-003',
        title: '深度学习进阶',
        description: '探索神经网络的奥秘，掌握深度学习前沿技术',
        thumbnail: './static/img/fm02.png',
        status: 'draft',
        duration: 90,
        teacher: {
          name: '王教授',
          avatar: 'static/img/teacher3.png',
          subject: '深度学习'
        },
        pptSlides: [
          {
            id: 'dl-slide-001',
            title: '神经网络原理',
            script: '神经网络是深度学习的基础，它模拟人脑神经元的工作方式。通过多层连接和非线性激活函数，实现复杂的模式识别。',
            slideType: 'title',
            displayDuration: 40,
            backgroundColor: '#667eea',
            textColor: '#ffffff',
            keywords: '神经网络,神经元,激活函数,模式识别',
            voiceType: 'female-professional',
            cameraShot: 'medium'
          },
          {
            id: 'dl-slide-002',
            title: '卷积神经网络',
            script: 'CNN是处理图像数据的强大工具，通过卷积层、池化层和全连接层的组合，能够自动提取图像特征并进行分类。',
            slideType: 'ppt',
            displayDuration: 55,
            backgroundColor: '#ffffff',
            textColor: '#333333',
            keywords: 'CNN,卷积层,池化层,图像特征,分类',
            voiceType: 'male-deep',
            cameraShot: 'ppt-focus'
          }
        ],
        stats: {
          totalSlides: 2,
          totalDuration: 95,
          studentsEnrolled: 67,
          completionRate: 78,
          averageScore: 82
        }
      }
    ]

    courses.forEach(course => {
      course.classroomSlides = this.generateClassroomSlides(course.pptSlides)
      this.courses.set(course.id, course)
    })
  }

  // 获取课程数据
  getCourse(courseId) {
    return this.courses.get(courseId)
  }

  // 获取所有课程
  getAllCourses() {
    return Array.from(this.courses.values())
  }

  // 获取课程的PPT讲稿数据（用于智慧课程管理）
  getCoursePPTSlides(courseId) {
    const course = this.courses.get(courseId)
    return course ? course.pptSlides : []
  }

  // 获取课程的3D课堂slides数据
  getCourseClassroomSlides(courseId) {
    const course = this.courses.get(courseId)
    return course ? course.classroomSlides : []
  }

  // 更新PPT讲稿（智慧课程管理中的修改）
  updatePPTSlide(courseId, slideId, updatedData) {
    const course = this.courses.get(courseId)
    if (!course) return false

    const slideIndex = course.pptSlides.findIndex(slide => slide.id === slideId)
    if (slideIndex === -1) return false

    // 更新PPT讲稿数据
    course.pptSlides[slideIndex] = { ...course.pptSlides[slideIndex], ...updatedData }
    
    // 同步更新3D课堂slides数据
    const classroomSlideIndex = course.classroomSlides.findIndex(slide => slide.id === slideId)
    if (classroomSlideIndex !== -1) {
      course.classroomSlides[classroomSlideIndex] = {
        ...course.classroomSlides[classroomSlideIndex],
        title: updatedData.title || course.classroomSlides[classroomSlideIndex].title,
        content: updatedData.script ? this.convertScriptToHTML(updatedData.script, updatedData.keywords) : course.classroomSlides[classroomSlideIndex].content,
        voiceScript: updatedData.script || course.classroomSlides[classroomSlideIndex].voiceScript,
        duration: updatedData.displayDuration || course.classroomSlides[classroomSlideIndex].duration,
        backgroundColor: updatedData.backgroundColor || course.classroomSlides[classroomSlideIndex].backgroundColor,
        textColor: updatedData.textColor || course.classroomSlides[classroomSlideIndex].textColor,
        keywords: updatedData.keywords ? updatedData.keywords.split(',').map(k => k.trim()) : course.classroomSlides[classroomSlideIndex].keywords
      }
    }

    // 通知监听器数据已更新
    this.notifyListeners('slideUpdated', { courseId, slideId, updatedData })
    return true
  }

  // 添加新的PPT讲稿
  addPPTSlide(courseId, slideData) {
    const course = this.courses.get(courseId)
    if (!course) return false

    const newSlide = {
      id: `slide-${Date.now()}`,
      title: slideData.title || '新讲稿',
      script: slideData.script || '',
      slideType: slideData.slideType || 'ppt',
      displayDuration: slideData.displayDuration || 30,
      backgroundColor: slideData.backgroundColor || '#ffffff',
      textColor: slideData.textColor || '#333333',
      keywords: slideData.keywords || '',
      voiceType: slideData.voiceType || 'female-professional',
      cameraShot: slideData.cameraShot || 'medium',
      transition: slideData.transition || 'fade',
      ...slideData
    }

    course.pptSlides.push(newSlide)
    
    // 同步添加到3D课堂slides
    const classroomSlide = {
      id: newSlide.id,
      title: newSlide.title,
      content: this.convertScriptToHTML(newSlide.script, newSlide.keywords),
      slideIndex: course.classroomSlides.length,
      duration: newSlide.displayDuration,
      voiceScript: newSlide.script,
      cameraShot: newSlide.cameraShot,
      transition: newSlide.transition,
      backgroundColor: newSlide.backgroundColor,
      textColor: newSlide.textColor,
      keywords: newSlide.keywords ? newSlide.keywords.split(',').map(k => k.trim()) : []
    }
    
    course.classroomSlides.push(classroomSlide)
    
    // 更新统计数据
    course.stats.totalSlides = course.pptSlides.length
    course.stats.totalDuration = course.pptSlides.reduce((total, slide) => total + slide.displayDuration, 0)

    this.notifyListeners('slideAdded', { courseId, slideData: newSlide })
    return newSlide.id
  }

  // 删除PPT讲稿
  deletePPTSlide(courseId, slideId) {
    const course = this.courses.get(courseId)
    if (!course) return false

    const slideIndex = course.pptSlides.findIndex(slide => slide.id === slideId)
    if (slideIndex === -1) return false

    course.pptSlides.splice(slideIndex, 1)
    
    // 同步删除3D课堂slides
    const classroomSlideIndex = course.classroomSlides.findIndex(slide => slide.id === slideId)
    if (classroomSlideIndex !== -1) {
      course.classroomSlides.splice(classroomSlideIndex, 1)
      // 重新设置slideIndex
      course.classroomSlides.forEach((slide, index) => {
        slide.slideIndex = index
      })
    }

    // 更新统计数据
    course.stats.totalSlides = course.pptSlides.length
    course.stats.totalDuration = course.pptSlides.reduce((total, slide) => total + slide.displayDuration, 0)

    this.notifyListeners('slideDeleted', { courseId, slideId })
    return true
  }

  // 获取课程统计数据
  getCourseStats(courseId) {
    const course = this.courses.get(courseId)
    return course ? course.stats : null
  }

  // 更新学习进度
  updateProgress(courseId, progressData) {
    const course = this.courses.get(courseId)
    if (!course) return false

    course.progress = { ...course.progress, ...progressData }
    this.notifyListeners('progressUpdated', { courseId, progress: course.progress })
    return true
  }

  // 添加数据变更监听器
  addListener(callback) {
    this.listeners.add(callback)
  }

  // 移除监听器
  removeListener(callback) {
    this.listeners.delete(callback)
  }

  // 通知所有监听器
  notifyListeners(event, data) {
    this.listeners.forEach(callback => {
      try {
        callback(event, data)
      } catch (error) {
        console.error('监听器回调错误:', error)
      }
    })
  }

  // 搜索课程
  searchCourses(query) {
    if (!query.trim()) return this.getAllCourses()
    
    const searchTerm = query.toLowerCase()
    return this.getAllCourses().filter(course => 
      course.title.toLowerCase().includes(searchTerm) ||
      course.description.toLowerCase().includes(searchTerm) ||
      course.teacher.name.toLowerCase().includes(searchTerm)
    )
  }

  // 根据状态筛选课程
  getCoursesByStatus(status) {
    return this.getAllCourses().filter(course => course.status === status)
  }

  // 获取热门课程（按学员数排序）
  getPopularCourses(limit = 5) {
    return this.getAllCourses()
      .sort((a, b) => b.stats.studentsEnrolled - a.stats.studentsEnrolled)
      .slice(0, limit)
  }

  // 获取推荐课程（按完成率和评分排序）
  getRecommendedCourses(limit = 3) {
    return this.getAllCourses()
      .sort((a, b) => {
        const scoreA = a.stats.completionRate * 0.6 + a.stats.averageScore * 0.4
        const scoreB = b.stats.completionRate * 0.6 + b.stats.averageScore * 0.4
        return scoreB - scoreA
      })
      .slice(0, limit)
  }

  // 发布课程
  publishCourse(courseId) {
    const course = this.courses.get(courseId)
    if (!course) return false

    course.status = 'published'
    this.notifyListeners('coursePublished', { courseId, course })
    return true
  }

  // 取消发布课程
  unpublishCourse(courseId) {
    const course = this.courses.get(courseId)
    if (!course) return false

    course.status = 'draft'
    this.notifyListeners('courseUnpublished', { courseId, course })
    return true
  }

  // 归档课程
  archiveCourse(courseId) {
    const course = this.courses.get(courseId)
    if (!course) return false

    course.status = 'archived'
    this.notifyListeners('courseArchived', { courseId, course })
    return true
  }
}

// 创建全局实例
const courseDataManager = new CourseDataManager()

export default courseDataManager 